<template>
  <div class="announcement-manage-container">
    <el-card>
      <div slot="header" class="clearfix">
        <span>公告管理</span>
        <el-button
          style="float: right; padding: 3px 0"
          type="text"
          @click="handleRefresh"
        >刷新</el-button>
      </div>
      
      <!-- 搜索区域 -->
      <el-form :inline="true" :model="queryParams" class="search-form">
        <el-form-item label="公告标题">
          <el-input v-model="queryParams.title" placeholder="请输入公告标题" clearable></el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
            <el-option label="已发布" value="PUBLISHED"></el-option>
            <el-option label="草稿" value="DRAFT"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="resetQuery">重置</el-button>
          <el-button type="success" @click="handleAdd">新增</el-button>
        </el-form-item>
      </el-form>
      
      <!-- 表格区域 -->
      <el-table
        :data="announcementList"
        border
        stripe
        style="width: 100%"
        v-loading="loading"
      >
        <el-table-column type="index" label="序号" width="50" align="center"></el-table-column>
        <el-table-column prop="title" label="公告标题" align="center"></el-table-column>
        <el-table-column prop="status" label="状态" align="center">
          <template slot-scope="scope">
            <el-tag type="success" v-if="scope.row.status === 'PUBLISHED'">已发布</el-tag>
            <el-tag type="info" v-else-if="scope.row.status === 'DRAFT'">草稿</el-tag>
            <el-tag v-else>未知</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" align="center">
          <template slot-scope="scope">
            {{ scope.row.createTime | formatDate }}
          </template>
        </el-table-column>
        <el-table-column prop="updateTime" label="更新时间" align="center">
          <template slot-scope="scope">
            {{ scope.row.updateTime | formatDate }}
          </template>
        </el-table-column>
        <el-table-column label="操作" :width="300" align="left">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="primary"
              @click="handleEdit(scope.row)"
              icon="el-icon-edit"
            >编辑</el-button>
            <el-button
              size="mini"
              type="danger"
              @click="handleDelete(scope.row)"
              icon="el-icon-delete"
            >删除</el-button>
            <el-button
              size="mini"
              type="success"
              v-if="scope.row.status === 'DRAFT'"
              @click="handlePublish(scope.row)"
              icon="el-icon-upload2"
            >发布</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryParams.pageNum"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="queryParams.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        class="pagination"
      ></el-pagination>
      
      <!-- 编辑公告对话框 -->
      <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="50%">
        <el-form :model="announcementForm" :rules="rules" ref="announcementFormRef" label-width="100px">
          <el-form-item label="公告标题" prop="title">
            <el-input v-model="announcementForm.title"></el-input>
          </el-form-item>
          <el-form-item label="公告内容" prop="content">
            <el-input type="textarea" v-model="announcementForm.content" rows="10"></el-input>
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-radio-group v-model="announcementForm.status">
              <el-radio label="PUBLISHED">发布</el-radio>
              <el-radio label="DRAFT">草稿</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </div>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  name: 'AnnouncementManage',
  data() {
    return {
      // 查询参数
      queryParams: {
        title: '',
        status: '',
        pageNum: 1,
        pageSize: 10
      },
      // 公告列表
      announcementList: [],
      // 总记录数
      total: 0,
      // 加载状态
      loading: false,
      // 对话框可见性
      dialogVisible: false,
      // 对话框标题
      dialogTitle: '',
      // 是否为编辑模式
      editMode: false,
      // 公告表单
      announcementForm: {
        id: '',
        title: '',
        content: '',
        status: 'DRAFT'
      },
      // 表单验证规则
      rules: {
        title: [
          { required: true, message: '请输入公告标题', trigger: 'blur' }
        ],
        content: [
          { required: true, message: '请输入公告内容', trigger: 'blur' }
        ],
        status: [
          { required: true, message: '请选择状态', trigger: 'change' }
        ]
      }
    }
  },
  created() {
    // 获取公告列表
    this.getAnnouncementList()
  },
  filters: {
    // 日期格式化过滤器
    formatDate(time) {
      if (!time) return ''
      const date = new Date(time)
      return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}:${String(date.getSeconds()).padStart(2, '0')}`
    }
  },
  methods: {
    // 获取公告列表
    async getAnnouncementList() {
      this.loading = true
      try {
        const { data: res } = await this.$http.get('/announcement/list', {
          params: this.queryParams
        })
        if (res.code !== 200) {
          return this.$message.error(res.message || '获取公告列表失败')
        }
        this.announcementList = res.data.records
        this.total = res.data.total
      } catch (error) {
        console.error('获取公告列表失败', error)
        this.$message.error('获取公告列表失败')
      } finally {
        this.loading = false
      }
    },
    // 处理查询
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getAnnouncementList()
    },
    // 重置查询
    resetQuery() {
      this.queryParams = {
        title: '',
        status: '',
        pageNum: 1,
        pageSize: 10
      }
      this.getAnnouncementList()
    },
    // 处理刷新
    handleRefresh() {
      this.getAnnouncementList()
    },
    // 处理页码变化
    handleCurrentChange(pageNum) {
      this.queryParams.pageNum = pageNum
      this.getAnnouncementList()
    },
    // 处理每页条数变化
    handleSizeChange(pageSize) {
      this.queryParams.pageSize = pageSize
      this.queryParams.pageNum = 1
      this.getAnnouncementList()
    },
    // 处理添加
    handleAdd() {
      this.dialogTitle = '添加公告'
      this.editMode = false
      this.announcementForm = {
        id: '',
        title: '',
        content: '',
        status: 'DRAFT'
      }
      this.dialogVisible = true
    },
    // 处理编辑
    handleEdit(row) {
      this.dialogTitle = '编辑公告'
      this.editMode = true
      this.announcementForm = { ...row }
      this.dialogVisible = true
    },
    // 处理删除
    handleDelete(row) {
      this.$confirm(`确认删除公告 ${row.title} 吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          const { data: res } = await this.$http.delete(`/announcement/${row.id}`)
          if (res.code !== 200) {
            return this.$message.error(res.message || '删除公告失败')
          }
          this.$message.success('删除公告成功')
          this.getAnnouncementList()
        } catch (error) {
          console.error('删除公告失败', error)
          this.$message.error('删除公告失败')
        }
      }).catch(() => {
        // 取消删除
      })
    },
    // 处理发布
    handlePublish(row) {
      this.$confirm(`确认发布公告 ${row.title} 吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          const { data: res } = await this.$http.put(`/announcement/publish/${row.id}`)
          if (res.code !== 200) {
            return this.$message.error(res.message || '发布公告失败')
          }
          this.$message.success('发布公告成功')
          this.getAnnouncementList()
        } catch (error) {
          console.error('发布公告失败', error)
          this.$message.error('发布公告失败')
        }
      }).catch(() => {
        // 取消发布
      })
    },
    // 提交表单
    submitForm() {
      this.$refs.announcementFormRef.validate(async valid => {
        if (!valid) return
        try {
          let res
          if (this.editMode) {
            // 编辑公告
            res = await this.$http.put('/announcement', this.announcementForm)
          } else {
            // 添加公告
            res = await this.$http.post('/announcement', this.announcementForm)
          }
          if (res.data.code !== 200) {
            return this.$message.error(res.data.message || '操作失败')
          }
          this.$message.success('操作成功')
          this.dialogVisible = false
          this.getAnnouncementList()
        } catch (error) {
          console.error('操作失败', error)
          this.$message.error('操作失败')
        }
      })
    }
  }
}
</script>

<style scoped>
.announcement-manage-container {
  padding: 20px;
}

.search-form {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}
</style>